package com.sparrow.preview;

import com.sparrow.config.EnvironmentVariables;
import com.sparrow.manage.article.ArticleService;
import com.sparrow.manage.common.service.impl.AttachmentService;
import com.sparrow.manage.company.CompanyService;
import com.sparrow.manage.template.data.strategy.CommonDataFetch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
@RequestMapping("/preview")
public class PreviewController {

    private static final Logger logger = LoggerFactory.getLogger(PreviewController.class);

    @Autowired
    private CompanyService companyService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private AttachmentService attachmentService;

    @RequestMapping("/{page}")
    public String preview(@PathVariable("page") String page, Model model){
        logger.info(page);

        CommonDataFetch dataFetch = new CommonDataFetch();
        dataFetch.setCompanyService(companyService);
        dataFetch.setArticleService(articleService);
        dataFetch.setAttachmentService(attachmentService);
        Map<String, Object> variables = dataFetch.getVariables();

        model.addAllAttributes(variables);
        int splitStart = page.indexOf("/");
        if(splitStart > 0){
            page = page.substring(0, splitStart);
        }else{
            splitStart = page.indexOf(".");
            if(splitStart > 0){
                page = page.substring(0, splitStart);
            }
        }
        model.addAttribute("source", page); // 不符合知道最小原则

        return EnvironmentVariables.PREVIEW_VIEW_TEMPLATE + page;
    }

}
